package com.example.travel.controller;

import com.example.travel.pojo.User;
import com.example.travel.service.UserService;
import com.example.travel.vo.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController  //等价于@ResponseBody+Controller，只返回数据
public class LoginController {


    @Autowired
    private UserService userService;

    //根据用户名和密码查询数据库用户
    @PostMapping("/toLogin")
    public ResultData<Object> findUser(String userName, String passWord, HttpServletRequest request){

        ResultData<Object> resultData = new ResultData<>();
        User user = new User();

        if (userName == null){
            resultData.setMsg("用户名不能为空，请输入用户名");
        }else if (!"".equals(userName)){

            if (passWord == null){
                resultData.setMsg("密码不能为空，请输入密码");
            }

            List<User> users = userService.findUser(userName);

            if (users.size() == 0){

                resultData.setMsg("用户名不存在");

            }else if (!"".equals(passWord)){
                user.setUserName(userName);
                user.setPassWord(passWord);

                List<User> userByUSAndPW = userService.getUserByUSAndPW(user);

                if (userByUSAndPW.size() == 0){
                    resultData.setMsg("用户名或密码错误！");
                }else if (userByUSAndPW.size() == 1){
                    resultData.setStatus(1);
                    resultData.setMsg("登录成功~");
                    //登录成功后存储用户的session值
                    request.getSession().setAttribute("user",userByUSAndPW.get(0));
                }
            }
        }

        return resultData;
    }

    //登录后获取用户数据
    @GetMapping("getUserInfo")
    public ResultData<Object> userInfo(HttpServletRequest request){

        Object user = request.getSession().getAttribute("user");

        ResultData<Object> resultData = new ResultData<>();

        resultData.setObj(user);

        return resultData;

    }
}
